<template>
  <!-- 接口管理  接口通-->
  <div class="app-container">
    <!-- 统计 -->
    <div class="card tongji">
      <subtit title="接口统计">
        <!-- <div class="flex">
          <div class="select flex">
            <div class="day1" @click="tongjiData.type=3;getOrderData(3)" :class="{active:tongjiData.type===3}">月</div>
            <div class="day2" @click="tongjiData.type=2;getOrderData(2)" :class="{active:tongjiData.type===2}">周</div>
            <div class="day3" @click="tongjiData.type=1;getOrderData(1)" :class="{active:tongjiData.type===1}">日</div>
            
          </div>
        </div> -->
      </subtit>

      <div class="cont_box flex">
        <div class="tongji-item flex">
          <img src="../../../assets/img/yikaitong.png" alt="">
          <div class="rg">
            <div class="tit">已开通</div>
            <div class="num">
              <count-to :start-val="0" :end-val="tongjiData.yikaitong" :duration="1000" class="card-panel-num" />
            </div>
          </div>
        </div>
        <div class="tongji-item bjsl flex">
          <img src="../../../assets/img/weikaitong.png" alt="">
          <div class="rg">
            <div class="tit">未开通</div>
            <div class="num">
              <count-to :start-val="0" :end-val="tongjiData.weikaitong" :duration="1000" class="card-panel-num" />
            </div>
          </div>
        </div>
        <!-- <div class="tongji-item wbjsl flex">
          <img src="../../../assets/img/shangjianum.png" alt="">
          <div class="rg">
            <div class="tit">上架数量</div>
            <div class="num">
              <count-to :start-val="0" :end-val="tongjiData.shangjiaCot" :duration="1000" class="card-panel-num" />
            </div>
          </div>
        </div>
        <div class="tongji-item zbsl flex">
          <img src="../../../assets/img/xiajianum.png" alt="">
          <div class="rg">
            <div class="tit">下架数量</div>
            <div class="num">
              <count-to :start-val="0" :end-val="tongjiData.xiajiaCot" :duration="1000" class="card-panel-num" />
            </div>
          </div>
        </div> -->
      </div>

     </div>

    <!-- 开通的接口 -->
     <div class="card alljiekou">
      <subtit title="API接口">
        <span style="color: #666;margin-left: 20px;">
          点击接口名称开通对应接口服务
        </span>
      </subtit>
      <div class="list-box flex" v-if="plantformList&&serviceList">
        <template   v-for="(item,index) in plantformList" >
          <div :key="index" @click="openInterface(item)" class="plantform-item" :class="{ykt:item.businessId}" v-if="item.isShow==1&&!item.isHide">
            {{item.name}}
            <!-- <span class="ykt" v-if="item.businessId">已开通 <span v-if="item.cont&&item.cont>1">{{item.cont}}</span></span> -->
          </div>
          
        </template>
      </div>

     </div>
     <div class="card alljiekou">
      <subtit title="客服上架接口">
        <span style="color: #666;margin-left: 20px;">
          如需开通，请联系商务。
        </span>
      </subtit>
      <div class="list-box flex" v-if="plantformList&&serviceList">
        <template   v-for="(item,index) in plantformList" >
          <div :key="index"  class="plantform-item" :class="{ykt:item.businessId}" v-if="item.isShow==1&&item.isHide">
            {{item.name}}
            <!-- <span class="ykt" v-if="item.businessId">已开通 <span v-if="item.cont&&item.cont>1">{{item.cont}}</span></span> -->
          </div>
          
        </template>
      </div>

     </div>


    <div class="jiekou_list_box">
      <subtit title="已开通接口">
      </subtit>
      <div style="margin-top: 10px;"></div>
      <el-form class="search-form-new" :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item el-form-item label="店铺" prop="merchantUserId" v-hasPermi="['searchTenantID']">
          <el-select v-model="queryParams.merchantUserId" placeholder="请选择店铺" clearable filterable size="small">
            <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="channelType">
          <el-select v-model="queryParams.channelType" placeholder="请选择类型" clearable @change="handleQuery">
            <el-option label="接口" :value="1" />
            <el-option label="客服上架" :value="2" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="销售伙伴" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入销售伙伴" clearable />
        </el-form-item> -->
        <el-form-item label="接口渠道" prop="interfaceUserName">
          <el-input v-model="queryParams.interfaceUserName" placeholder="请输入销售商" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
            <el-option v-for="dict in statusList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <!-- <el-button v-hasPermi="['partner:partner:add']" type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button> -->
          <!-- <el-button v-hasPermi="['partner:partner:edit']" type="warning" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button> -->
          
          <!-- <el-button v-hasPermi="['partner:partner:deleteErr']" type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDeleteErr">重推失败条目</el-button> -->
          
           
        </el-form-item>
      </el-form>
      <div class="table_box table_box_new">
        <!-- <div class="tip">
          本页面进行接口推送配置，如果推送不成功，请检查接口参数配置是否正确！
        </div> -->
        <el-table border stripe v-loading="loading" :data="partnerList" >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="序号" align="center" prop="id" width="80" />
          <el-table-column label="类型" align="center" prop="channelType">
            <template slot-scope="scope">
              <div>
                {{ scope.row.channelType == 2 ? "客服上架" : "接口" }}
              </div>
            </template>
          </el-table-column>
          

          <el-table-column label="名称" align="center" prop="name" min-width="150" />
          <el-table-column label="接口渠道" align="center" prop="interfaceUserName" min-width="100" />
          <el-table-column label="供货人" align="center" prop="merchantUserName" min-width="130" />
          
          <!-- <el-table-column label="CODE" align="center" prop="saleName" /> -->
          <el-table-column label="价格类型" align="center" prop="pricePushType">
            <template slot-scope="scope">
              <div>
                {{ scope.row.pricePushType == 2 ? "供货价推送" : "加价推送" }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="系统状态" align="center" prop="status" width="90">
            <template slot-scope="scope">
              <div>
                <el-tag type="success" v-if="scope.row.status==1">可用</el-tag>
                <el-tag type="danger" v-if="scope.row.status==2">禁用</el-tag>
              </div>
            </template>
            
          </el-table-column>
          <el-table-column label="" align="center" prop="cotMap">
            <template slot="header">
              <el-popover
                placement="top-start"
                title="应对接数量"
                width="200"
                trigger="hover"
                content="符合渠道现推送配置条件的商品数量。">
                <span slot="reference">应对接数量
                  <i class="el-icon-question"></i>
                </span>
              </el-popover>
            </template>
            <template slot-scope="scope">
              <div class="link" v-if="scope.row.cotMap&&scope.row.cotMap.cot>0" @click="openQudaoGoods(scope.row)">
                {{ scope.row.cotMap.duijieCot||'--' }} / {{ scope.row.cotMap.cot||'--' }}
              </div>
              <div v-else>
                --
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="已对接数量" align="center" prop="cotMap">
            <template slot="header">
              <el-popover
                placement="top-start"
                title="已对接数量"
                width="200"
                trigger="hover"
                content="当前渠道已对接的所有的商品数量。">
                <span slot="reference">已对接数量
                  <i class="el-icon-question"></i>
                </span>
              </el-popover>
            </template>
            <template slot-scope="scope">
              <div class="link" v-if="scope.row.cotMap&&scope.row.cotMap.yiduijieCot>0" @click="openQudaoGoods(scope.row,'yiduijie')">
                {{ scope.row.cotMap.yiduijieCot||'--' }}
              </div>
              <div v-else >
                --
              </div>
            </template>
          </el-table-column> -->

          <!-- <el-table-column label="创建人" align="center" prop="createName" /> -->
          <el-table-column label="到期时间" align="center" prop="closeTime" width="100" />
          <el-table-column label="自动续费" align="center" prop="isAuto">
            <template slot-scope="scope">
              <el-switch
                @change="editAuto($event,scope.row)"
                :disabled="nowDate==scope.row.closeTime"
                v-model="scope.row.isAuto"
                :active-value="1"
                :inactive-value="2"
                active-color="#24A813"
                inactive-color="#999999">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column  label="操作" min-width="200">
            <template slot-scope="scope">
              <!-- @click="handleUpdate" -->
              <el-button type="text"  v-hasPermi="['partner:partner:edit']" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="text"  @click="openPushConfig(scope.row)">推送配置</el-button>
              <el-button type="add" v-hasPermi="['account:rec:list']" v-if="(checkPermi(['account:rec:list'])&&scope.row.channelType==1)||(checkPermi(['account:scriptPushRec:list'])&&scope.row.channelType==2)" icon="el-icon-remove-outline"  @click="goRecords(scope.row)">查看记录</el-button>
              <br/>
              <el-button v-hasPermi="['partner:partner:deleteErr']" type="del"  icon="el-icon-delete" @click="handleDeleteErr(scope.row)">失败重推</el-button>
              <el-button v-hasPermi="['partner:partner:remove']" type="del" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              

              <el-button v-hasPermi="['add:price:remove']" type="del" plain icon="el-icon-delete" :loading="exportLoading" @click="rmRec(scope.row)">一键重推</el-button>
              <el-button v-if="checkPermi(['partner:partner:xufei'])&&scope.row.channelType==1"   type="add"  @click="xufeiApi(scope.row)">续费</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination :autoScroll="false" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>
    <!-- 添加或修改销售伙伴对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div class="flex" style="height: calc(100vh - 260px); overflow-y: auto;width:100%">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="width:100%">
          <div class="flex" style="width:100%;justify-content: space-between;">
            <div>
              <el-form-item label="供货商" prop="merchantUserId" v-if="userInfo.tenantId == 1">
                <el-select style="width: 250px" filterable v-model="form.merchantUserId" placeholder="请选择供货商" clearable @change="merchantUserIdChange">
                  <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
                </el-select>
              </el-form-item>
              <el-form-item label="接口渠道" prop="interfaceUserId">
                <el-select style="width: 250px" v-if="userInfo.tenantId == 1" filterable v-model="form.interfaceUserId" placeholder="请选择接口渠道" clearable @change="interfaceUserIdChange($event,2)">
                  <el-option v-for="dict in interfaceChannelList" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
                <span v-else>{{ form.interfaceUserName }}</span>
              </el-form-item>
              <el-form-item label="CODE" prop="saleName">
                <el-input style="width: 250px" disabled v-model="form.saleName" placeholder="请输入CODE" />
              </el-form-item>
              <el-form-item label="名称" prop="name">
                <el-input style="width: 250px" v-model="form.name" placeholder="请输入接口名称" />
              </el-form-item>
              <el-form-item label="价格类型" prop="pricePushType">
                <el-select style="width: 250px" v-model="form.pricePushType" placeholder="价格类型" clearable>
                  <el-option :label="'统一加价'" :value="1" />
                  <el-option :label="'原价推送'" :value="2" />
                  <el-option :label="'阶梯加价'" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status" v-hasPermi="['partner:partner:changeState']">
                <el-select style="width: 250px" v-model="form.status" placeholder="请选择状态" clearable>
                  <el-option v-for="dict in statusList" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>
            </div>
            <div class="channelInfo" v-if="curChanelInfo">
              <el-descriptions class="margin-top" title="渠道详情" :column="1" border>
                <el-descriptions-item label="渠道名称">{{
              curChanelInfo.name
            }}</el-descriptions-item>
                <el-descriptions-item label="对接游戏">{{
              curChanelInfo.gameNames
            }}</el-descriptions-item>
                <el-descriptions-item label="联系方式">{{
              curChanelInfo.contact
            }}</el-descriptions-item>
                <el-descriptions-item label="技术联系方式">{{
              curChanelInfo.serviceContact
            }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>

          <el-form-item v-if="form.pricePushType == 1" label="上调比例(%)" prop="seleep">
            <el-input type="number" style="width: 217px" v-model="form.seleep" placeholder="请输入上调比例" />
          </el-form-item>

          <div class="rule-box" v-if="form.pricePushType == 3">
            <div class="tip">
              1、可以设置多个加价规则；每行可以设置xxx~xxx价格的商品,加价百分比和最低加价金额；所有输入框都是必填项。<br />
              2、推送时根据商品金额匹配到加价规则，进行相应的加价。<br />
              3、每行规则含义：符合 最小价格&lt;=商品金额&lt;最大价格 的商品按照该行的规则进行加价。<br />
              4、如果加价百分比为负数，即降价推送，最低加价金额无效。<br />
              5、匹配不到规则的商品，按照原价推送。<br />
            </div>
            <draggable v-model="ruleList" handle=".move" forceFallback="true" group="people" animation="300" @start="onStart" @end="onEnd">
              <transition-group>
                <div class="rule-item flex" v-for="(item,index) in ruleList" :key="index">
                  <div class="move">
                    <i class="el-icon-sort"></i>
                  </div>
                  <div class="flex">
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.minAmount" placeholder="最小价格" style="width:100px" />
                    <span style="margin:0 5px"> - </span>
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.maxAmount" placeholder="最大价格" style="width:100px" />
                    <span>，加价</span>
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.rate" placeholder="" style="width:80px" />
                    <span>%，最低加价</span>
                    <el-input-number :precision="0" :controls="false" @change="inputChange" v-model="item.zuidiAmount" placeholder="" style="width:100px" />
                    <span>元。</span>
                    <el-button v-if="index!=0" style="margin-left:15px" size="mini" @click="removeRule(index)" icon="el-icon-delete" plain>移除</el-button>
                  </div>
                </div>
              </transition-group>
            </draggable>
            <div style="text-align:right">
              <el-button @click="addRule" type="primary" size="small">新增</el-button>
            </div>
          </div>
          <!-- 接口参数 -->
          <div v-if="config && config.length">
            <el-divider content-position="left">接口参数(请联系对应渠道获取)</el-divider>
            <el-form-item v-for="(attr, i) in config" :key="i" :label="attr.name" :prop="attr.key">
              <el-input type="textarea" style="width: 400px" v-model="form['' + attr.key]" :placeholder="'请输入' + attr.name" />
            </el-form-item>
          </div>
        </el-form>

      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <pushConfigDialog ref="pushConfigDialog"></pushConfigDialog>
    <template v-if="shopInfo">
      <apiOpenDialog :tenantId="userInfo.tenantId" :campNumber="shopInfo.campNumber" ref="apiOpenDialog" @success="init"></apiOpenDialog>
    </template>

    <el-dialog title="一键重推" width="500px" :visible.sync="rmRecVisible" append-to-body>
      <label for="">
        <SPAN>选择渠道：</SPAN>
        <el-select disabled filterable v-model="delPartId" placeholder="请选择渠道" clearable @change="qudaoChange">
          <el-option v-for="dict in saleList" :key="dict.id" :label="dict.name" :value="dict.saleName" />
        </el-select>
      </label>
      <div style="margin-top:15px"></div>
      <label for="" >
        <SPAN>选择游戏：</SPAN>
        <el-select  filterable v-model="delGameName" placeholder="请选择游戏" clearable >
          <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.name" />
        </el-select>
      </label>

      <div class="tip" style="margin-top: 15px;text-align: left;color: #666;"> <span style="color: red;">提示：</span> 该操作会将选中的渠道所有推送记录删掉，并重新推送所有符合规则的商品。<br/>
        请确保该操作前，<span style="color: red;">已在对方平台全部下架或删除你的商品</span> ，否则会造成商品重复推送，导致失败！请谨慎操作！</div>
      <div slot="footer" class="dialog-footer">

        <el-button @click="rmRecVisible = false">取 消</el-button>
        <el-button type="primary" @click="rmRecSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="失败重推" width="500px" :visible.sync="shibaiVisible" append-to-body>
      <label for="">
        <SPAN>接口渠道：</SPAN>
        <span>{{ curQudao }}</span>
      </label>
      <div style="margin-top:15px"></div>
      <label for="" >
        <SPAN>选择游戏：</SPAN>
        <el-select  filterable v-model="delGameName" placeholder="请选择游戏" clearable >
          <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.name" />
        </el-select>
      </label>

      <div class="tip" style="margin-top: 15px;text-align: left;color: #666;"> <span style="color: red;">提示：</span> 该操作会将选中的渠道失败的推送记录删掉，并重新推送失败的商品。
        </div>
      <div slot="footer" class="dialog-footer">

        <el-button @click="shibaiVisible = false">取 消</el-button>
        <el-button type="primary" @click="shibaiSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <qudaoGoodsDialog ref="qudaoGoodsDialog"></qudaoGoodsDialog>
    
  </div>
</template>

<script>
import {
  listPartner,
  getPartner,
  delPartner,
  addPartner,
  updatePartner,
  handleDeleteErrRepush,
  updateStateByConfigId,
  allList
} from "@/api/partner/partner";
import {
  delRecNew,
  scriptdelAllOut
} from "@/api/info/rec";
// import interfaceChannelApi2 from "@/api/interfaceChannel/index";
import interfaceChannelApi from "@/api/shanghuduan/interfaceChannel.js";
import valueAddedServices from '@/api/shanghuduan/valueAddedServices'
import { mapGetters } from "vuex";
import pushConfigDialog from "../push/pushConfigDialog.vue";
import subtit from "@/components/indexComponents/subtit.vue";
//导入draggable组件
import draggable from "vuedraggable";

import apiOpenDialog from "../../../components/tenant/apiOpenDialog.vue";
import CountTo from "vue-count-to";
import { formatDate } from "@/utils/index";
import qudaoGoodsDialog from "./qudaoGoodsDialog.vue";
export default {
  name: "Jiekoutong",
  components: { pushConfigDialog, draggable ,subtit,apiOpenDialog,CountTo,qudaoGoodsDialog},
  data() {
    return {
      shibaiVisible:false,
      rmRecVisible:false,
      saleList: [],
      delPartId:'',
      delGameName:'',
      curQudao:'',


      plantformList:null,//所有的接口渠道平台
      myServiceList:null,//已开通的接口服务
      serviceList:[],
      tongjiData:{
        type:1,
        weikaitong:0,
        yikaitong:0,
        shangjiaCot:0,
        xiajiaCot:0,

      },


      codeIs: false,
      formName: {},
      openName: false,
      titleName: "",
      nameList: [],
      intername: false,
      parterShow: true,
      statusList: [
        {
          id: "1",
          name: "可用",
        },
        {
          id: "2",
          name: "禁用",
        },
      ],
      isMonthList: [
        {
          id: 1,
          name: "是",
        },
        {
          id: 2,
          name: "否",
        },
      ],
      supplyList: [],
      saleNameDis: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售伙伴表格数据
      partnerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      queryNameParams: {
        pageNum: 1,
        name: null,
        code: null,
      },
      interNameRow: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createId: null,
        updateId: null,
        name: null,
        saleKey: null,
        other: null,
        twoOther: null,
        threeOther: null,
        ishulian:1
      },
      allUsers: [],
      interfaceChannelList: [],
      config: [], //接口参数配置的字段
      // 表单参数
      form: {
        pricePushType: 2,
      },
      // 表单校验
      rules: {
        pricePushType: [
          { required: true, message: "请选择价格类型", trigger: "change" },
        ],
        interfaceUserName: [
          { required: true, message: "请选择接口渠道", trigger: "change" },
        ],
      },
      curChanelInfo: "",
      ruleList: [
        {
          minAmount: 0,
          maxAmount: "",
          sort: 0,
          zuidiAmount: "",
          rate: "",
        },
      ],
      drag: false,
      nowDate:'',
      rmRecType:''
    };
  },
  created() {
    let date = new Date()
    this.nowDate = formatDate(date).slice(0,10)
    this.init();
    // this.getOrderData()
    this.allSale()
  },
  computed: {
    ...mapGetters(["userInfo", "shopInfo", "tenantList"]),
    allGameList() {
      return this.$store.getters.allGameList;
    },
  },
  methods: {
    init(){
      this.getList();
      this.getQudaoList();
      this.kaitongtongji()
      
      
    },
    // 打开渠道 商品列表
    openQudaoGoods(row,flag){
      this.$refs.qudaoGoodsDialog.open(row,flag)
    },
    allSale() {
      allList({
        channelType: '',
      }).then((res) => {
        if (res.code == 200) {
          this.saleList = res.rows;
        }
      });
    },
    // 接口开通数量统计
    kaitongtongji(){
      interfaceChannelApi.kaitongtongji().then(res=>{
        this.tongjiData.weikaitong = res.data.weikaitong
        this.tongjiData.yikaitong = res.data.yikaitong
      })
    },
    // 获取顶部统计
    getOrderData(){
      interfaceChannelApi.shangxiajiatongji({
        type:this.tongjiData.type
      }).then(res=>{
        this.tongjiData.xiajiaCot = res.data.xiajiaCot
        this.tongjiData.shangjiaCot = res.data.shangjiaCot
      })
    },
    // 查看推送记录
    goRecords(row){
      if(row.channelType==2){
        this.$router.push({
          name:'ScriptPushRec',
          query:{
            salecode:row.saleName
          }
        })
      }else{
        this.$router.push({
          name:'Rec/index',
          query:{
            salecode:row.saleName
          }
        })
      }
    },
     // 改变自动续费状态
     editAuto(e,row){
      if(this.myServiceList&&this.myServiceList.length){
        this.myServiceList.forEach(r=>{
          if(r.id==row.valueAddedServiceId){
            r.isAuto = e
            valueAddedServices.myValueAddedServiceChangeAuto(r).then(res=>{
              this.getList()
            })
          }
        })
      }else{
        this.$message.error('未开通服务，不能改变自动续费状态！')
      }
      
    },
    // 续费API
    xufeiApi(item){

      
      if(this.myServiceList&&this.myServiceList.length){
        this.myServiceList.forEach(r=>{
          if(r.id==item.valueAddedServiceId){
            this.$refs.apiOpenDialog.open(r,2)
          }
        })
      }else{
        this.$message.error('未开通服务，不能续费！')
      }
    },
    // 开通接口渠道
    openInterface(item){
      let type=1
      if(item.serveType) type = item.serveType
      this.$refs.apiOpenDialog.open(item,1,type)
    },
     // 获取所有的接口渠道
     getQudaoList(){
        this.loading = true;
        interfaceChannelApi.getAllList({isPage:2}).then(res=>{
          this.plantformList = res.rows
          this.interfaceChannelList = JSON.parse(JSON.stringify(res.rows))
          // console.log("%c Line:356 🍉 res.rows", "color:#33a5ff", res.rows);
            this.getMyService(this.userInfo.tenantId)
            this.loading = false;
        })
      
      },
    // 获取租户开通的增值服务
    getMyService(tenantId){
      // if()
      valueAddedServices.myValueAddedServiceList({
        dataType: 'all',
        tenantId: tenantId,
        type:2
      }).then(res=>{
        if(res.rows&&res.rows.length){
          this.serviceList = res.rows
        }else{
          this.serviceList = []
        }
        this.mergeServices()
      })
    },
    // 合并获取到的已开通服务和全部服务列表
    mergeServices(){
      if(this.serviceList&&this.serviceList.length){
        this.myServiceList = this.serviceList
          this.plantformList.forEach((r1,i1)=>{
            let cont = 0
            if(r1.channelType==2){
              r1.isHide = true
            }
            this.serviceList.forEach((r2,i2)=>{
              if(r1.id==r2.businessId){
                cont++
                this.plantformList[i1] = {...r1,...r2}
                this.myServiceList[i2] = {...r1,...r2}
              }
            })
            if(cont){
              this.plantformList[i1].cont = cont
            }
          })
        
      }else{
        this.plantformList.forEach((r1,i1)=>{
            if(r1.channelType==2){
              r1.isHide = true
            }
          })
      }
      this.$forceUpdate()
    },
    // //属性校正（仅限多选）
    // shuxingjCheckBox(item) {
    //   this.$router.push({
    //     path: '/api/index/SXJZJXDX',
    //     query: {
    //       Id: item.id,
    //       Name: item.name
    //     }
    //   })
    // },

    // 打开推送配置
    openPushConfig(row) {
      this.$refs.pushConfigDialog.open(row);
    },

    // 获取所有接口渠道
    getQudaoList2() {
      // interfaceChannelApi2
      //   .interfaceChannelList({ isPage: 2, isShow: 1 })
      //   .then((response) => {
      //     this.interfaceChannelList = response.rows;
      //     console.log("%c Line:429 🌮 response.rows", "color:#2eafb0", response.rows);
      //   });
    },
    // 选择供货商改变
    merchantUserIdChange(e) {
      if (e) {
        this.tenantList.forEach((r) => {
          if (r.tenantId == e) {
            this.form.merchantUserName = r.tenantName;
            this.form.tenantId = e;
          }
        });
      } else {
        this.form.merchantUserName = "";
      }
    },
    // 阶梯加价相关
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
      this.ruleList.forEach((r, i) => {
        r.sort = i;
      });
    },
    inputChange() {
      this.setRuleStr();
      // this.$refs..resetFields()
      // this.$refs.form2.validate(valid=>{})
    },
    // 添加一条规则
    addRule() {
      let lth = this.ruleList.length;
      this.ruleList.push({
        minAmount: lth > 0 ? this.ruleList[lth - 1].maxAmount : "",
        maxAmount: "",
        sort: 999,
        zuidiAmount: "",
        rate: "",
      });
    },
    //移除一条规则
    removeRule(index) {
      this.ruleList.splice(index, 1);
      this.setRuleStr();
    },
    validateRule() {
      let pass = true;
      if (this.ruleList && this.ruleList.length) {
        this.ruleList.forEach((r) => {
          if (
            !(r.minAmount || r.minAmount == 0) ||
            !r.maxAmount ||
            !r.zuidiAmount ||
            !r.rate
          ) {
            pass = false;
          }
        });
      } else {
        pass = false;
      }
      return pass;
    },
    // 处理规则字符串
    setRuleStr() {
      this.ruleList.forEach((r, i) => {
        r.sort = i;
      });
      this.form.rule = JSON.stringify(this.ruleList);
    },

    // 阶梯加价结束
    // 选择渠道改变
    interfaceUserIdChange(e, flag) {
      if (e) {
        this.interfaceChannelList.forEach((r) => {
          if (r.id == e) {
            if (r.code) {
              this.curChanelInfo = r;
              if (flag == 2) {
                this.form.saleName = this.form.merchantUserId + "_" + r.code;
                this.form.name = this.form.merchantUserName + "_" + r.name;
                this.form.interfaceUserName = r.name;
              }
            } else {
              if (flag == 2) {
                this.form.interfaceUserName = "";
                this.form.interfaceUserId = "";
                this.form.saleName = "";
                this.form.name = "";
              }
              return this.$alert("该接口渠道配置有误，请联系管理员处理。");
            }
            this.config = JSON.parse(r.configTemplate);
            if (this.config && this.config.length) {
              for (let i = 0; i < this.config.length; i++) {
                let attr = this.config[i];
                if (!attr.isShow) {
                  this.config.splice(i, 1);
                  i--;
                } else if (attr.isShow && attr.isMust) {
                  this.rules[attr.key] = [
                    {
                      required: true,
                      message: "请输入" + attr.name,
                      trigger: "blur",
                    },
                  ];
                } else {
                  if (this.rules[attr.key]) delete this.rules[attr.key];
                }
              }
            }
          }
        });
      } else {
        this.form.interfaceUserName = "";
      }
    },

    /** 查询销售伙伴列表 */
    getList() {
      this.loading = true;
      listPartner(this.queryParams).then((response) => {
        this.partnerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.config = [];
      this.form = {
        id: null,
        createId: null,
        updateId: null,
        saleName: null,
        name: null,
        saleKey: null,
        other: null,
        twoOther: null,
        threeOther: null,
        createTime: null,
        updateTime: null,
        pricePushType: 2,
        merchantUserId: "",
        merchantUserName: "",
      };
      this.ruleList = [
        {
          minAmount: 0,
          maxAmount: "",
          sort: 0,
          zuidiAmount: "",
          rate: "",
        },
      ];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售伙伴";
      this.$nextTick(() => {
        // 供货商 merchantUserId merchantUserName
        if (this.shopInfo && this.shopInfo.tenantId) {
          this.form.merchantUserId = this.shopInfo.tenantId;
          this.form.merchantUserName = this.shopInfo.tenantName;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPartner(id).then((response) => {
        this.form = response.data;
        // this.form.merchantUserId = String(this.form.merchantUserId)
        this.open = true;
        if (this.form.rule) {
          this.ruleList = JSON.parse(this.form.rule);
        }
        this.title = "修改销售伙伴";
        this.$nextTick(() => {
          this.interfaceUserIdChange(this.form.interfaceUserId);
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (
          valid &&
          (this.form.pricePushType != 3 ||
            (this.form.pricePushType == 3 && this.validateRule()))
        ) {
          this.setRuleStr();
          // 处理填写的参数，去掉前后空格和换行
          if (this.config && this.config.length){
            for (let i = 0; i < this.config.length; i++) {
              let attr = this.config[i];
              if(this.form[attr.key]) this.form[attr.key] = this.form[attr.key].trim()
            }
          }
          if (this.form.id != null) {
            updatePartner(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPartner(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    qudaoChange(e){
      console.log("%c Line:903 🍎 e", "color:#4fff4B", e);

    },
    // 一键重推
    rmRecSubmit() {
      if(this.rmRecType==1){
        delRecNew(this.delPartId,this.delGameName)
        .then(() => {
          this.delPartId = "";
          this.rmRecVisible = false;
          this.$modal.msgSuccess("一键重推成功");
        })
        .catch(() => {});
      }else if(this.rmRecType==2){
        scriptdelAllOut(this.delPartId,this.delGameName)
        .then(() => {
          this.delPartId = "";
          this.rmRecVisible = false;
          this.$modal.msgSuccess("一键重推成功");
        })
        .catch(() => {});
      }
      
    },
    // 点击一键重推按钮
    rmRec(row) {
      this.rmRecType = row.channelType
      this.delPartId = row.saleName;
      this.delGameName = '';
      this.rmRecVisible = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除销售伙伴编号为"' + ids + '"的数据项？')
        .then(function () {
          return delPartner(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  
    /** 点击失败重推按钮 */
    handleDeleteErr(row) {
      this.delPartId = row.id;
      this.delGameName = '';
      this.curQudao = row.name
      this.shibaiVisible = true;
    },
    // 失败重推
    shibaiSubmit(){
      handleDeleteErrRepush({
        gameName:this.delGameName,
        configId:this.delPartId
      })
        .then(() => {
          this.curQudao = ''
          this.delGameName = ''
          this.delPartId = "";
          this.shibaiVisible = false;
          this.$modal.msgSuccess("失败重推成功");
        })
        .catch(() => {});
    }
  },
};
</script>
<style  lang="scss" scoped>
.tip {
  text-align: right;
  color: #ff0000;
  font-size: 14px;
}
.app-container{
  background-color: transparent;
  padding: 0;
  padding-bottom: 20px;
  .card{
    background: #fff;
    border-radius: 10px;
    padding: 15px;
  }
  .tongji{
    .select {
      margin-left: 15px;
      > div {
        border: 1px solid #ccc;
        border-right: none;
        padding: 3px 20px;
        cursor: pointer;
        color: #4E5969;
        font-size: 14px;
        &:last-child {
          border-right: 1px solid #D8DCE6;
          border-radius: 0 3px 3px 0;
        }
        &:first-child {
          border-radius: 3px 0 0 3px;
        }
        &.active {
          border-color: #6C5DD3;
          background: #6C5DD3;
          color: #fff;
        }
      }
    }
    .cont_box {
    flex-wrap: nowrap;
    align-items: center;
    padding-top: 15px;
    
    .tongji-item {
      // min-width: 200px;
      width: 50%;
      background: #eafce8;
      border-radius: 8px;
      // justify-content: center;
      padding-left: 30px;
      align-items: center;
      margin-right: 20px;
      height: 120px;
      // width: 25%;
      color: #333;
      &.bjsl {
        background: #fff8ec;
      }
      &.wbjsl {
        background: #a0d7e7;
      }
      &.zbsl {
        background: #7fba7a;
      }
      img {
        width: 70px;
        height: 70px;
        margin-right: 15px;
      }
      .tit {
        font-weight: bold;
        font-size: 16px;

        height: 30px;
        line-height: 40px;
        color: #999;
      }
      .num {
        font-weight: 500;
        font-size: 30px;
        line-height: 50px;
      }
    }
  }
  }
  .alljiekou{
    padding-bottom: 0;
    margin-top: 8px;
    .list-box{
      flex-wrap: wrap;
      margin-top: 15px;
    }
    .plantform-item{
      width: 106px;
      height: 36px;
      background: #F7FBFF;
      border-radius: 4px;
      border: 1px solid #D9DCE4;
      text-align: center;
      white-space: nowrap;
      line-height: 36px;
      margin-bottom: 8px;
      margin-right: 8px;
      overflow: hidden;
      text-overflow: ellipsis;
      padding: 0 10px;
      position: relative;
      cursor: pointer;
      &.ykt{
        background-image: url('../../../assets/img/kaitongbg.png');
        background-size: 100% 100%;
        color: #6C5DD3;
      }
    }
  }

  .jiekou_list_box{
    background-color: #fff;
    margin-top: 10px;
    padding:15px;
    border-radius: 10px;
    .table_box{
      padding: 0;
      border-radius: 0;
      box-shadow: none;
    }
  }
}
.channelInfo {
  width: 400px;
  background: #fff;
  margin: 10px;
  /* position: absolute;
  right: 15px;
  top: 15px; */
}
.rule-box {
  width: 80%;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  .tip {
    text-align: left;
  }
}
.rule-item {
  /* margin-bottom: 20px; */
  border-bottom: 1px solid #ccc;
  padding: 10px;
  align-items: center;
  > .flex {
    align-items: center;
  }
}
.rule-item:last-of-type {
  border: none;
}
.rule-item .move {
  text-align: center;
  width: 30px;
  height: 30px;
  line-height: 30px;
  cursor: pointer;
  background-color: #46a6ff;
  color: #fff;
  font-size: 20px;
  border-radius: 50%;
  margin-right: 10px;
}
</style>
